#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import re

import scrapy
from urllib.parse import unquote

from parsel import Selector
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, base64
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class YunnanYnsczt9ef7Policy(BaseTaxPolicySpider):
    name = 'yunnan_ynsczt_9ef7_policy'

    source = '云南省财政厅'
    province = '云南省'
    city = ''
    county = ''
    park = ''

    def start_requests(self):
        url = 'https://czt.yn.gov.cn/jeecg-boot/index/tbArticle/listRegulatory?pageNo=1&pageSize=10'
        yield scrapy.Request(url, callback=self.parse_list)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        for elem in response.json()['result']['records']:
            item = Item()
            item['source_url'] = 'https://czt.yn.gov.cn/gfxwj-desc.html?id=' + elem['id']
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem['createTime']
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            # print(item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            total_page = response.json()['result']['pages']
            print(total_page)
            for page_num in range(2, int(int(total_page) / 1 + 1)):
                yield response.follow(re.sub(r"pageNo=1", r"pageNo={}".format(page_num), response.url),
                                      callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()

        item['content'] = response.xpath(""".""").get()
        item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl yunnan_ynsczt_9ef7_policy".split())
